<template>
  <!-- 约课管理 -->
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="89px"
    >
      <el-form-item label="课程名称" prop="memberTypeName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
      </el-form-item>
    </el-form>
    <!-- 新增按钮模块 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button
        >
      </el-col>
    </el-row>
    <!-- 列表数据展示 -->
    <el-table
      v-loading="loading"
      :data="courseList"
      :header-cell-class-name="'headerBg'"
      class="bold-header"
      @selection-change="handleSelectionChange"
    >
      <!--      <el-table-column type="index" width="55" align="center"/>-->


      <el-table-column label="课程名称" align="center" prop="courseName" :show-overflow-tooltip="true"/>
      <el-table-column
        label="课程图片"
        align="center"
        key="coverPic"
        prop="coverPic"
        width="130">
        <template slot-scope="scope">
          <el-carousel height="80px" width="80px" v-if="scope.row.coverPic">
            <el-carousel-item
              v-for="item in scope.row.coverPic.split(',')"
              :key="item"
            >
              <ImagePreview :src="String(item)"></ImagePreview>
            </el-carousel-item>
          </el-carousel>
          <el-tag v-else type="info">暂无数据</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="课程时间" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.courseStartTime + "~" + scope.row.courseEndTime }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="课程创建时间" align="center" prop="courseCreateTime" :show-overflow-tooltip="true"/>
      <el-table-column label="课程最大报名人数" align="center" prop="registrationNumber" :show-overflow-tooltip="true"/>
      <el-table-column prop="collectFee" label="是否收费" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_course_collect_fee" :value="scope.row.collectFee"/>
          <!--          <el-tag type="danger" v-if="scope.row.collectFee === 0"> 收费 </el-tag>-->
          <!--          <el-tag type="success" v-else> 免费 </el-tag>-->
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="liveRoomStatus"
        label="启用/禁用">
        <!-- 滑块开关 -->
        <!--        <template slot-scope="scope">-->
        <!--          <el-tag type="success" v-if="scope.row.courseStatus === 1"> 停用</el-tag>-->
        <!--          <el-tag type="danger" v-else> 正常</el-tag>-->
        <!--        </template>-->
        <template slot-scope="scope">
          <el-switch v-model="scope.row.courseStatus"
                     active-color="#ff4949"
                     inactive-color="#13ce66"
                     :active-value="1"
                     :inactive-value="0"
                     @change=toggleDisableStatus(scope.row)>
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRead(scope.row)"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button
          >
          <el-button
            style="color: red;"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改窗口 -->
    <el-dialog :title="title" :visible.sync="open" @close="close" width="850px" append-to-body>
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="rules"
        label-width="100px"
        class="form-container"
        :inline="true"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="courseName">
              <el-input
                v-model="addForm.courseName"
                placeholder="请输入课程名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程状态" prop="collectFee">
              <el-select v-model="addForm.courseStatus">
                <el-option label="正常" :value=0></el-option>
                <el-option label="停用" :value=1></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否收费" prop="collectFee">
              <el-select v-model="addForm.collectFee">
                <el-option label="收费" :value=0></el-option>
                <el-option label="免费" :value=1></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收费金额" prop="collectFeeMoney">
              <el-input v-model="addForm.collectFeeMoney" placeholder="元" maxlength="4">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="至少报名数" prop="registrationNumberLeast">
              <el-input v-model="addForm.registrationNumberLeast" placeholder="人" maxlength="4">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大报名数" prop="registrationNumber">
              <el-input v-model="addForm.registrationNumber" placeholder="人" maxlength="4">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程报名时间" prop="registrationTime">
              <el-date-picker
                v-model="addForm.registrationTime"
                type="datetime"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程截止报名时间" prop="registrationDeadline">
              <el-date-picker
                v-model="addForm.registrationDeadline"
                type="datetime"
                placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程开始时间" prop="courseStartTime">
              <el-time-picker v-model="addForm.courseStartTime" format="HH:mm:ss" value-format="HH:mm:ss"
                              :picker-options='{"selectableRange":"00:00:00-23:59:59"}' :style="{width: '100%'}"
                              placeholder="请选择时间选择" clearable></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程结束时间" prop="courseEndTime">
              <el-time-picker v-model="addForm.courseEndTime" format="HH:mm:ss" value-format="HH:mm:ss"
                              :picker-options='{"selectableRange":"00:00:00-23:59:59"}' :style="{width: '100%'}"
                              placeholder="请选择时间选择" clearable></el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程图片">
              <el-upload
                class="avatar-uploader"
                action=""
                :multiple="true"
                :on-remove="handleRemove"
                :on-change="handlechange"
                list-type="picture-card"
                :before-upload="beforeAvatarUpload"
                accept=".jpg,.jpeg,.png,.gif"
                :auto-upload="false"
                :file-list="fileList"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程描述" prop="courseDescribe">
              <el-input v-model="addForm.courseDescribe" type="textarea" placeholder="请输入课程描述"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="button-container" style="text-align: right;">
          <el-button @click="cancelAll">取消</el-button>
          <el-button type="primary" @click="submitForm('form')">提交</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 查看详情对话框 -->
    <el-dialog title="器材详情" :visible.sync="dialogTableVisible">
      <el-descriptions class="margin-top" :column="2" :size="size" border>
        <el-descriptions-item>
          <template slot="label">
            课程名称
          </template>
          {{ courseInfoData.courseName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            课程描述
          </template>
          {{ courseInfoData.courseDescribe }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            课程创建时间
          </template>
          {{ courseInfoData.courseCreateTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            活动最大报名人数
          </template>
          {{ courseInfoData.registrationNumber }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            至少报名人数
          </template>
          {{ courseInfoData.registrationNumberLeast }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            是否收费
          </template>
          <el-tag v-if="courseInfoData.collectFee == '0'" type="danger">收费</el-tag>
          <el-tag v-else type="success">免费</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="courseInfoData.collectFee == '0'">
          <template slot="label">
            <i class="el-icon-money"></i>
            收费金额
          </template>
          {{ courseInfoData.collectFeeMoney }}元
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            课程状态
          </template>
         <el-tag v-if="courseInfoData.courseStatus == '0'">正常</el-tag>
         <el-tag v-else type="warning">停用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            课程开始时间
          </template>
          {{ courseInfoData.courseStartTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            课程结束时间
          </template>
          {{ courseInfoData.courseEndTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            课程报名时间
          </template>
          {{ courseInfoData.registrationTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            课程截止报名时间
          </template>
          {{ courseInfoData.registrationDeadline }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            课程图片
          </template>
          <el-carousel width="100px" v-if="courseInfoData.coverPic">
            <el-carousel-item
              v-for="item in courseInfoData.coverPic.split(',')"
              :key="item"
            >
              <ImagePreview :src="String(item)"></ImagePreview>
            </el-carousel-item>
          </el-carousel>
          <el-tag v-else type="info">暂无数据</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!--分页效果-->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    >
    </pagination>
  </div>
</template>
<script>
import {
  getCourseList,
  getCourseInfoById,
  addCourse,
  updateCourseById,
  delCourse,
  updateCourseStatus
} from "@/api/courseSubscribe/index";
import {Message} from "element-ui";

export default {
  name: 'index',
  dicts: ['sys_course_collect_fee'],
  data() {
    return {
      courseInfoData:{},
      delImageIds: [],
      imageUrl: "",
      imageFile: File,
      imgUrl: process.env.VUE_APP_IMG_BASE_URL,
      //存储图片数组
      fileList: [],
      coverPic: '',//课程图片
      // 租户标识
      venueUniqueIdentifier: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 表格数据
      courseList: [],
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        venueUniqueIdentifier: '',
        courseName: '',//课程名称
        // 第几页
        pageNum: 1,
        // 每页条数
        pageSize: 10,
        // // 总条数
        // total: 0,
      },
      // 总条数
      total: 0,
      // 当前页码
      currentPage4: 1,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogTableVisible: false,
      // 表单参数
      addForm: {},
      size: '',
      // 表单校验
      rules: {
        registrationTime: [{required: true, message: "请填写报名", trigger: "blur"}],
        registrationDeadline: [{required: true, message: "请填写截止时间", trigger: "blur"}],
        courseStartTime: [{required: true, message: "请填写课程开始时间", trigger: "blur"}],
        courseEndTime: [{required: true, message: "请填写课程结束时间", trigger: "blur"}],
        registrationNumber: [{required: true, message: "请填写报名人数", trigger: "blur"}],
        registrationNumberLeast: [{required: true, message: "请填写最少报名人数", trigger: "blur"}],
        collectFee: [{required: true, message: "请选择是否收费", trigger: "blur"}],
        courseStatus: [{required: true, message: "请选择课程状态", trigger: "blur"}],
        collectFeeMoney: [{required: true, message: "请输入收费金额", trigger: "blur"}],
        courseName: [
          {required: true, message: "请输入课程名称", trigger: "blur"},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        courseDescribe: [{required: true, message: "请输入课程描述", trigger: "blur"},
          {min: 5, max: 50, message: '不少于5个字符', trigger: 'blur'}]
      },
    };
  },
  created() {
    if (sessionStorage.getItem('venueUniqueIdentifier')) {
      this.venueUniqueIdentifier = sessionStorage.getItem('venueUniqueIdentifier');
    }

    this.getList(this.venueUniqueIdentifier);
  },
  methods: {
    //日期时间转换
    dateTimeTransition(date) {
      // 获取年、月、日、时、分、秒
      var year = date.getFullYear();
      var month = ('0' + (date.getMonth() + 1)).slice(-2);
      var day = ('0' + date.getDate()).slice(-2);
      var hours = ('0' + date.getHours()).slice(-2);
      var minutes = ('0' + date.getMinutes()).slice(-2);
      var seconds = ('0' + date.getSeconds()).slice(-2);

// 格式化日期字符串
      var formattedDateString = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
      return formattedDateString;
    },
    // 图片上传之前的校验方法
    beforeAvatarUpload(file) {
      const isPNG = file.type === "image/png";
      const isJPG = file.type === "image/jpg";
      const isJPEG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isJPG && !isPNG && !isJPEG) {
        this.$message.error("上传图片只能是 JPG,格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
      this.imgCarousel = file;
      this.carouselImg = URL.createObjectURL(file);
      return false;
    },
    // 模糊查询操作
    handleQuery() {
      const that = this;
      this.getList()
    },
    // 全查操作
    getList() {
      const that = this;
      this.loading = true;
      this.queryParams.venueUniqueIdentifier = this.venueUniqueIdentifier;
      getCourseList(this.queryParams)
        .then((res) => {
          this.courseList = res.data.content;
          this.total = res.data.totalSize;
          this.loading = false;
        });
    },
    // 查询一条操作
    handleFind(row) {
      this.title = "查看约课信息";
      this.open = true;
      this.loading = true;
      this.shaoSaveButton = false;
      const id = row.id
      const venueUniqueIdentifier = this.venueUniqueIdentifier
      getCourseInfoById(id, venueUniqueIdentifier).then((res) => {
        // this.coverPic = "http://101.43.223.224:8765/image/getImageById?id=" + res.data.coverPic
        this.addForm = res.data;
        this.loading = false;
      });
    },
    // 修改按钮操作
    handleUpdate(row) {
      if (row.courseStatus === 1) {
        // 添加判断条件
        this.open = true;
        this.handleFind(row);
        this.title = "修改约课信息";
        const that = this;
        this.reset();
        this.addForm = JSON.parse(JSON.stringify(row));
        const coursePhotos = row.coverPic;
        if (coursePhotos != 'null' && coursePhotos != undefined) {
          const coursePhotoIds = coursePhotos.split(',');
          if (coursePhotoIds.length > 0) {
            coursePhotoIds.forEach(id => {
              if (id !== '') {
                this.fileList.push({url: that.imgUrl + id, id: id});
              }
            });
          }
        }
      } else {
        // isDisable 不等于 1，不能打开修改窗口
        Message.error("该课程正在进行，无法修改操作！！！");
      }
    },
    // 删除
    handleDelete(row) {
      const that = this;
      if (row.courseStatus === 0) {
        Message.error("该课程正在进行，无法删除操作！！！");
      } else {
        this.$confirm("此操作将永久删除 '"+ row.courseName+"' 课程, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            delCourse(row.id, row.venueUniqueIdentifier)
              .then((res) => {
                this.$message({type: "success", message: "删除成功"});
                that.getList();
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    // 提交按钮
    submitForm() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          if (this.fileList.length > 5) {
            this.$modal.msgError("上传图片不能超过5张");
            return false;
          }
          this.addForm.venueUniqueIdentifier = this.venueUniqueIdentifier
          var formdata = new FormData();
          formdata.set("id", this.addForm.id);
          formdata.set("courseName", this.addForm.courseName);
          formdata.set("courseDescribe", this.addForm.courseDescribe);
          formdata.set("registrationNumber", this.addForm.registrationNumber);
          formdata.set("registrationNumberLeast", this.addForm.registrationNumberLeast);
          formdata.set("collectFee", this.addForm.collectFee);
          formdata.set("collectFeeMoney", this.addForm.collectFeeMoney);
          formdata.set("courseStatus", this.addForm.courseStatus);
          formdata.set("venueUniqueIdentifier", this.venueUniqueIdentifier);
          formdata.set("courseStartTime", this.addForm.courseStartTime);
          formdata.set("courseEndTime", this.addForm.courseEndTime);
          if (this.fileList.length > 0) {
            this.fileList.forEach((item) => {
              formdata.append("files", item.raw);
            });
          }
          if (this.addForm.id != null && this.addForm.id != null && this.addForm.id != undefined) {
            formdata.set("coverPic", this.addForm.coverPic);
            console.log(this.addForm.coverPic)
            formdata.set("registrationDeadline", this.addForm.registrationDeadline);
            formdata.set("registrationTime", this.addForm.registrationTime);
            // 修改方法
            updateCourseById(
              formdata
            )
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message({type: "success", message: "修改成功"});
                  // 关闭窗口
                  this.open = false;
                  //刷新
                  this.getList();
                } else {
                  this.$message.error({type: "warning", message: "修改失败"});
                }
              });
          } else {
            formdata.set("id", 0)
            var newRegistrationTime = this.dateTimeTransition(this.addForm.registrationTime)
            var newRegistrationDeadline = this.dateTimeTransition(this.addForm.registrationDeadline)
            formdata.set("registrationDeadline", newRegistrationDeadline);
            formdata.set("registrationTime", newRegistrationTime);
            addCourse(formdata)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message({type: "success", message: "添加成功"});
                  // 关闭窗口
                  this.open = false;
                  //刷新
                  this.getList();
                } else {
                  this.$message.error({type: "warning", message: "添加失败"});
                }
              });
          }
        }
      });
    },
    handleRead(row) {
      this.dialogTableVisible = true;
      this.courseInfoData = JSON.parse(JSON.stringify(row));
    },
    // 取消按钮
    cancelAll() {
      this.open = false;
    },
    close() {
      this.fileList = [];
      this.imageUrl = ""
      this.open = false;
    },
    // 新增按钮操作
    handleAdd() {
      this.open = true;
      this.title = "添加课程信息";
      // 清除表单数据
      this.reset();
      // if (this.$refs.addForm !== undefined) {
      //   this.$refs.addForm.resetFields();
      // }
      this.addForm.id = null
    },
    // 启用禁用状态按钮
    toggleDisableStatus(row) {
      const id = row.id;
      const courseStatus = row.courseStatus;
      const venueUniqueIdentifier = row.venueUniqueIdentifier
      if (row.courseStatus === 1) {
        updateCourseStatus(
          id,
          courseStatus,
          venueUniqueIdentifier
        )
          .then((res) => {
            console.log(res.data)
            if (res.data === "null") {
              this.$message({type: "error", message: "禁用失败"});
              this.getList();
            } else {
              this.$message({type: "error", message: "禁用成功"});
              this.getList();
            }

            // 处理成功
          });
      } else {
        updateCourseStatus(
          id,
          courseStatus,
          venueUniqueIdentifier
        )
          .then((res) => {
            this.$message({type: "success", message: "启用成功"});
            this.getList();
            // 处理成功
          });
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.lid);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 分页每页条数显示
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
      console.log(`每页 ${val} 条`);
    },
    // 分页当前页显示
    handleCurrentChange(val) {
      this.currentPage4 = val;
      this.queryParams.pageNum = val;
      this.getList();
      console.log(`当前页: ${val}`);
    },
    handlechange(fileList) {
      // 将原有的图片存入fileList中
      this.fileList.push(fileList);
    },
    handleRemove(file) {
      // 删除照片
      if (file.id) {
        const coursePhoto = this.addForm.coverPic;
        let arrImgIds = coursePhoto.split(",");
        arrImgIds = arrImgIds.filter((item) => {
          return item !== file.id && item !== "";
        });
        this.delImageIds.push(file.id)
        const index = this.fileList.indexOf(file);
        if (index !== -1) {
          this.fileList.splice(index, 1);
        }
        this.addForm.coverPic = arrImgIds.join(",");
      } else {
        this.fileList = this.fileList.filter((item) => {
          return file.name !== item.name && file.url !== item.url;
        });
      }
    },
    // 表单重置
    reset() {
      this.fileList = [];
      this.form = {};
      this.resetForm("addForm");
    },
  },
};
</script>
<style>
.headerBg {
  background: #eee !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.bold-header .el-table__header th {
  font-weight: bold;
}

.button-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
